﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using System.Web;


/// <summary>
///ExtendMethod 的摘要说明
/// </summary>
public static class ExtendMethod
{
    public static string ToFriendlyTime(this DateTime dt)
    {
        return ToFriendlyTime(dt, 0);
    }

    /// <summary>
    /// 友好显示时间
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="type">0:默认,1左侧最近来访使用</param>
    /// <returns></returns>
    public static string ToFriendlyTime(this DateTime dt, int type)
    {
        TimeSpan span = DateTime.Now - dt;
        string returnStr = "";

        DateTime theDay = DateTime.Now.Date;
        DateTime yesterdayDt = theDay.AddDays(-1);
        // DateTime dayBeforeYesterdayDt = yesterdayDt.AddDays(-1);

        switch (type)
        {
            case 0:
                if (span.TotalMinutes < 1)
                {
                    returnStr = "刚刚";
                }
                else if (span.TotalHours < 1)
                {
                    returnStr = string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
                }
                else if ((dt - theDay).TotalMilliseconds >= 0)
                {
                    returnStr = dt.ToString("今天HH:mm");
                }
                else if ((dt - yesterdayDt).TotalMilliseconds >= 0)
                {
                    returnStr = dt.ToString("昨天HH:mm");
                }
                else
                {
                    returnStr = dt.ToString("yyyy年MM月dd日 HH:mm");
                }
                break;
            case 1:
                if (span.TotalMinutes < 1)
                {
                    returnStr = "刚刚";
                }
                else if (span.TotalHours < 1)
                {
                    returnStr = string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
                }
                else if ((dt - theDay).TotalMilliseconds >= 0)
                {
                    returnStr = dt.ToString("今天HH:mm");
                }
                else if ((dt - yesterdayDt).TotalMilliseconds >= 0)
                {
                    returnStr = dt.ToString("昨天HH:mm");
                }
                else
                {
                    returnStr = dt.ToString("MM月dd日");
                }
                break;
            default:
                break;
        }
        return returnStr;
    }





    public static string ToShortTime(this DateTime? dt)
    {
        if (dt == null)
        {
            return "";
        }
        DateTime tdt = dt ?? DateTime.Now;
        return tdt.ToString("yyyy年MM月dd日");
    }

    //截断显示
    //public static string ToLeft(this string str, int num)
    //{
    //    str = str.Trim();
    //    if (string.IsNullOrEmpty(str))
    //        return string.Empty;
    //    str = str.Replace("<", "&lt;").Replace(">", "&gt;").Replace(" ", "&nbsp;").Replace("\t", "").Replace("\n", "&nbsp;").Replace("'", "&#39;").Replace("\"", "&#34;");
    //    str = IOWeb.Dirty2Text(str);
    //    if (str.Length > num)
    //    {
    //        str = str.Substring(0, num) + "...";
    //    }

    //    return str;
    //}


    ////通用显示
    //public static string ToHtml(this string str)
    //{
    //    str = str.Trim();
    //    if (string.IsNullOrEmpty(str))
    //        return string.Empty;
    //    str = str.Replace("<", "&lt;").Replace(">", "&gt;").Replace(" ", "&nbsp;").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").Replace("\n", "&nbsp;").Replace("'", "&#39;").Replace("\"", "&#34;");
    //    str = IOWeb.Dirty2Text(str);
    //    //str = IOWeb.TextByImg(str);            
    //    return str;
    //}

    ////内容显示
    //public static string ToContentHtml(this string str)
    //{
    //    str = str.Trim();
    //    if (string.IsNullOrEmpty(str))
    //        return string.Empty;
    //    str = str.Replace("<", "&lt;").Replace(">", "&gt;").Replace(" ", "&nbsp;").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").Replace("\n", "&nbsp;").Replace("'", "&#39;").Replace("\"", "&#34;");
    //    str = IOWeb.Dirty2Text(str);
    //    str = IOWeb.TextByImg(str);
    //    str = AnalyticsTopic(str);
    //    return str;
    //}


    /// <summary>
    /// 清除html标签
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    //public static string ClearHtml(this string str)
    //{
    //    if (!string.IsNullOrEmpty(str))
    //    {
    //        return RegexComm.GetRegexReplacedValue(str, "<[^>]+>", "", RegexOptions.IgnoreCase);
    //    }

    //    return "";
    //}


    // 检测话题
    //public static string AnalyticsTopic(string msg)
    //{
    //    // 检测话题
    //    var ms = Regex.Matches(msg, "#([.:/\\w-]+)#", RegexOptions.IgnoreCase);

    //    string listTopic = msg;
    //    foreach (Match m in ms)
    //    {
    //        try
    //        {
    //            string topic = m.Groups[1].Value;
    //            string allStr = string.Format("<a href='/HotTopic.aspx?topic={1}'>#{0}#</a>", topic, System.Web.HttpUtility.UrlEncode(topic));
    //            listTopic = listTopic.Replace('#' + topic + '#', allStr);
    //        }
    //        catch
    //        {
    //        }
    //    }
    //    return listTopic;
    //}




    //短消息转义
    //public static string ToMessageHtml(this string str)
    //{
    //    str = str.Trim();
    //    if (string.IsNullOrEmpty(str))
    //        return string.Empty;
    //    str = str.Replace("<", "&lt;").Replace("\r\n", "<br/>").Replace(">", "&gt;").Replace(" ", "&nbsp;").Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").Replace("\n", "<br/>").Replace("'", "&#39;").Replace("\"", "&#34;");
    //    str = IOWeb.Dirty2Text(str);
    //    //str = IOWeb.TextByImg(str);
    //    return str;
    //}



    public static string SafeString(this string str)
    {
        str = str.Trim();
        return System.Web.HttpUtility.HtmlEncode(str);

    }

    public static string TOJSON(this object obj)
    {
        string rtn = string.Empty;
        System.Web.Script.Serialization.JavaScriptSerializer js = new JavaScriptSerializer();

        rtn = js.Serialize(obj);
        return rtn.ToLower();
    }


    public static string TOJSON(this object obj, int RecursionLimit)
    {
        string rtn = string.Empty;
        System.Web.Script.Serialization.JavaScriptSerializer js = new JavaScriptSerializer();
        js.RecursionLimit = RecursionLimit;
        rtn = js.Serialize(obj);
        return rtn.ToLower();
    }


    public static T JSONToObject<T>(this string jsonString)
    {
        if (string.IsNullOrEmpty(jsonString))
            return default(T);

        System.Web.Script.Serialization.JavaScriptSerializer js = new JavaScriptSerializer();



        return js.Deserialize<T>(jsonString);
    }



    public static string FormatSelf(this string obj, params object[] args)
    {
        return string.Format(obj, args);
    }

    public static List<T> ToList<T>(this IEnumerable<T> data)
    {
        var list = new List<T>();

        if (data != null)
            list.AddRange(data);

        return list;
    }


    public static DateTime ToDateTime(this string dateString)
    {
        if (string.IsNullOrEmpty(dateString))
            return default(DateTime);

        DateTime dt;
        DateTime.TryParse(dateString, out dt);

        return dt;
    }



    #region ---序列化---

    public static string SerializeToString(this object obj)
    {
        var ctx = System.Web.HttpContext.Current;
        if (ctx == null || ctx.Request == null)
        {
            return SerializeToString(obj, Common.Serialization.SerializationType.Xml);
        }
        else
        {
            string serializationType = ctx.Request["SerializationType"]??string.Empty;            
            Common.Serialization.SerializationType stype;
            switch (serializationType.ToLower())
            {
                case "xml":
                    stype = Common.Serialization.SerializationType.Xml;
                    break;
                case "json":
                    stype = Common.Serialization.SerializationType.Json;
                    break;
                default:
                    stype = Common.Serialization.SerializationType.Xml;
                    break;
            }

            return SerializeToString(obj, stype);
        }
    }

    public static string SerializeToString(this object obj, Common.Serialization.SerializationType stype)
    {
        return Common.Serialization.SimpleSerialization.Serialize(obj, stype);
    }

    #endregion
}